import UserController from '@/services/user';
import { IUser } from '@/types/user';
import { PageContainer } from '@ant-design/pro-components';
import { useNavigate, useParams } from '@umijs/max';
import { message } from 'antd';
import React, { useEffect, useState } from 'react';
import UserForm from '../components/UserForm';

const EditUser: React.FC = () => {
  const navigate = useNavigate();
  const { userid } = useParams();

  const [userInfo, setUserInfo] = useState({
    loginId: '',
    loginPwd: '',
    avatar: '',
    nickname: '',
    mail: '',
    qq: '',
    wechat: '',
    intro: '',
  } as IUser);

  useEffect(() => {
    async function fetchData() {
      if (userid) {
        const { data } = await UserController.getUserById(userid);
        setUserInfo(data);
      }
    }
    fetchData();
  }, [userid]);

  /**
   * 提交新增用户
   */
  function handleSubmit(value: any) {
    if (
      value.avatar &&
      typeof value.avatar === 'object' &&
      value.avatar.file.status === 'done'
    ) {
      value.avatar = value.avatar.file.response.data;
    }
    if (!userid) return;
    UserController.editUser(userid, value);
    // 跳转回首页
    navigate('/user/user-list');
    message.success('编辑用户成功');
  }

  return (
    <PageContainer>
      <div className="container" style={{ width: '800px' }}>
        <UserForm type="edit" userInfo={userInfo} handleSubmit={handleSubmit} />
      </div>
    </PageContainer>
  );
};

export default EditUser;
